package jdktcp.client;

import org.apache.commons.io.IOUtils;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class JDKTcpClient {

    static int SIZE = 1;

    static ExecutorService pool = Executors.newFixedThreadPool(10);
    static int timeout = 1000 * 10;

    static String host = "localhost";
    static int port = 9999;

    public static void main(String[] args) throws Exception {
        for (int i = 0; i < SIZE; i++) {
            pool.execute(new SocketClietHandler());
        }
    }

    private static class SocketClietHandler implements Runnable {
        @Override
        public void run() {
            try (Socket client = new Socket()) {

                client.setSoTimeout(timeout);
                client.setSoLinger(true, 0);
                client.connect(new InetSocketAddress(host, port), timeout);
                System.out.println("start connect to:" + host + ":" + port);

                sendAndRevice(client);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private static void sendAndRevice(Socket client) throws Exception {
        System.out.println("connect:" + client);
        OutputStream out = client.getOutputStream();
        out.write(50);
        out.write(("HelloA").getBytes());
        out.write(("HelloB").getBytes());
        out.flush();

        //没有长度约定情况下,需要主动关闭输出流,让服务端知晓客户端数据传输完毕
        client.shutdownOutput();

        InputStream in = client.getInputStream();
        byte[] buff = IOUtils.toByteArray(in);
        System.out.println("response==>" + new String(buff));
    }
}
